#!/usr/local/bin/ruby
#
#  Copyright (c) 2009 Mu Dynamics, Inc. All rights reserved.

require 'ddt_api'

class RunsController < ApplicationController

  attr_accessor :mu_ip

  # GET /runs
  # GET /runs.xml
  def index

    find_params = { :include => params[:id] }.merge( order_by )
    @runs = Run.find :all, find_params

    # @runs = Run.all

    if params.key?("clear_templates")
      Run.clear_templates
    end

    if params.key?("mu_ip")
      logger.debug "runscontroller.index calling run.populate called with #{params[:mu_ip]}"
      Run.populate(params[:mu_ip])
    end

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @runs }
    end

    if params.key?("execute")
      # logger.debug("woah, execute!")
      execute(params[:run])
    end

    if params.key?("populate")
      # logger.debug("woah, populate")
      populate
    end

  end

  # GET /runs/1
  # GET /runs/1.xml
  def show
    @run = Run.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @run }
    end
  end

  # GET /runs/new
  # GET /runs/new.xml
  def new
    @run = Run.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @run }
    end
  end

  # GET /runs/1/edit
  def edit
    @run = Run.find(params[:id])
  end

  # POST /runs
  # POST /runs.xml
  def create
    @run = Run.new(params[:run])
    
    # if Get Templates button was pressed
    if params.key?("commit")
      if params[:commit].include?("Set IP")
        runparams = params[:run]
        $mu_ip = runparams['mu_ip'].strip
        Run.populate($mu_ip)
        redirect_to(@run)
        return
      end
    end

    # all drop downs must have selected something or else do nothing ...
    if @run['scenario_name'] == $select_one or
       @run['testsuite_name'] == $select_one
         on_error
         return
    end

    # fill in template uuid's from template names
    if @run['scenario_uuid'] == "" or !params[:run].key?('scenario_uuid')
      @run['scenario_uuid'] = Run.scenarios[@run['scenario_name']]
      logger.debug "scenario = #{@run['scenario_name']}, #{@run['scenario_uuid']}"
    end

    if @run['testsuite_uuid'] == "" or !params[:run].key?('testsuite_uuid')
      @run['testsuite_uuid'] = Run.testsuites[@run['testsuite_name']]
      logger.debug "testsuite = #{@run['testsuite_name']}, #{@run['testsuite_uuid']}"
    end

    # temporarily get a new DdtApi object and set up a session in order to get hosts info
    @api = DdtApi.new($mu_ip)
    @api.new_session
    @api.load_scenario(@run['scenario_uuid'])
    roles = ""
    hosts = @api.get_hosts
    @api.close_session

    # parse the role names out of the get_hosts response
    hosts.each do | h |
      role = h["role"]
      logger.debug role
      roles = roles + role + ","
    end
    roles = roles[0, roles.length - 1]
    logger.debug "==> runs_controller.create: roles = #{roles}"

    # save the run to the database
    params = {}
    params["mu_ip"] = $mu_ip
    params["host_names"] = nil # to be set later, in edit
    params["host_roles"] = roles
    params["host_types"] = nil # no longer used
    params["scenario_name"] = @run['scenario_name']
    params["scenario_uuid"] = @run['scenario_uuid']
    params["testsuite_name"] = @run['testsuite_name']
    params["testsuite_uuid"] = @run['testsuite_uuid']
    @run.save_run(params)

    respond_to do |format|
      flash[:notice] = 'Success: Run was created and saved.'
      format.html { redirect_to(@run) }
      format.xml  { render :xml => @run, :status => :created, :location => @run }
    end
  end

  def on_error
     flash[:notice] = 'On Error: there is something wrong in the form'
     render :action => "new"
  end

  # PUT /runs/1
  # PUT /runs/1.xml
  def update
    @run = Run.find(params[:id])

    logger.debug "scenario = " + @run['scenario_name']

    # logger.debug(params)
    host_names = []
    host_roles = []
    params.sort.each do | k, v |
      $DEBUG and puts "==> ==> runs_controller.updatem params: #{k} => #{v}"
      if k.match(/^host_/)
        p = k.split("_")
        host_names << v
        host_roles << p[1]
        $DEBUG and puts "==> runs_controller.update: host name = #{v}, host role = #{p[1]}"
      end
    end

    # convert the arrays into comma-separated strings for the database
    names = ""

    @run['host_names'] = Array.new
    host_names.each do | h |
      names = names + h + ","
    end
    names = names[0, names.length - 1]
    @run['host_names'][0] = names

    logger.debug "==> runs_controller.update: host names = #{@run['host_names'][0]}"
    logger.debug "==> runs_controller.update: host roles = #{@run['host_roles'][0]}"

    uparams = {}
    uparams["run_id"] = params[:id]
    uparams["mu_ip"] = @run['mu_ip']
    uparams["host_names"] = names
    uparams["scenario_name"] = @run['scenario_name']
    uparams["scenario_uuid"] = @run['scenario_uuid']
    uparams["testsuite_name"] = @run['testsuite_name']
    uparams["testsuite_uuid"] = @run['testsuite_uuid']
    # update the database
    @run.update_run(uparams)

    respond_to do |format|
#      if @run.update_attributes(params[:run])
        flash[:notice] = 'Run was successfully updated.'
        format.html { redirect_to(runs_path) }
        format.xml  { head :ok }
    end
  end

  # DELETE /runs/1
  # DELETE /runs/1.xml
  def destroy
    @run = Run.find(params[:id])
    @run.destroy

    respond_to do |format|
      format.html { redirect_to(runs_url) }
      format.xml  { head :ok }
    end
  end

  def execute(run_id)
    logger.debug "in runs controller, execute"
    @run = Run.find(run_id)
    @run.execute(run_id)
  end

  def clear_templates
    Run.clear_templates
  end

  def populate(mu_ip=ENV['MU_IP'])
    logger.debug "runscontroller.populate calling run.populate called with #{$mu_ip}"
    Run.populate(mu_ip)
  end
end
